﻿using Microsoft.Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
using Swashbuckle.Swagger;
using Topshelf;

namespace aier.wx.api.selfhost
{
	/// <summary>
	/// 
	/// </summary>
	public class HeaderMiddleware : OwinMiddleware
	{
		private const string WWWAuthenticateHeader = "WWW-Authenticate";
		public HeaderMiddleware(OwinMiddleware next) : base(next)
		{ }
		public override Task Invoke(IOwinContext context)
		{
			if (context.Request.Uri.PathAndQuery.Contains("/swagger"))
			{
				string authHeader = context.Request.Headers["Authorization"];
				if (authHeader != null && authHeader.StartsWith("Basic "))
				{
					// Get the credentials from request header
					var header = AuthenticationHeaderValue.Parse(authHeader);
					var inBytes = Convert.FromBase64String(header.Parameter);
					var credentials = Encoding.UTF8.GetString(inBytes).Split(':');
					var username = credentials[0];
					var password = credentials[1];
					// validate credentials
					if (username.Equals("admin")
					  && password.Equals("qzwang@123"))
					{

						return Next.Invoke(context);
					}
				}
				var host = string.Format("Basic realm=\"{0}\"", "no auth");
				context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
				context.Response.Headers.Add(WWWAuthenticateHeader, new string[] { host });
			
			}
		    return Next.Invoke(context);
		}
	}
}
